package com.kgcx.dbutils.config;

import com.kgcx.common.listener.ApplicationStartUp;
import com.kgcx.dbutils.interceptor.QueryInterceptor;
import com.kgcx.dbutils.interceptor.UpdateInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Properties;

@Component
public class PluginConfig {


    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;

    @PostConstruct
    public void addPageInterceptor() {

        /**
         * mybatis插件的加载机制是后进先执行,所以把此插件放到容器加载完成后创建
         * 目的是为了此插件在分页插件后被添加进mybatis插件队列,这样插件的执行顺序就先于分页插件
         */
        ApplicationStartUp.addFunction(() -> {
            QueryInterceptor queryInterceptor = new QueryInterceptor();
            Properties properties = new Properties();
            //先把一般方式配置的属性放进去
            //properties.putAll(pageHelperProperties());
            //在把特殊配置放进去，由于close-conn 利用上面方式时，属性名就是 close-conn 而不是 closeConn，所以需要额外的一步
            //properties.putAll(this.properties.getProperties());
            queryInterceptor.setProperties(properties);

            UpdateInterceptor updateInterceptor = new UpdateInterceptor();
            for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
                sqlSessionFactory.getConfiguration().addInterceptor(queryInterceptor);
                sqlSessionFactory.getConfiguration().addInterceptor(updateInterceptor);
            }
        });
    }


}
